package club.hicode.daydayup.netty.demo.server;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 处理类
 *
 * @author Liu Chunfu
 * @date 2018-06-14 下午3:15
 **/
@Slf4j
public class MyHandler extends SimpleChannelInboundHandler<String> {

    ExecutorService executorService = Executors.newCachedThreadPool();

    private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        //ctx.channel().eventLoop().scheduleAtFixedRate(()->{
        //    String msg2 = System.currentTimeMillis() + " From " + msg;
        //    ctx.channel().writeAndFlush(msg2);
        //    System.out.println("current thread is "+Thread.currentThread().getId());
        //},2,2,TimeUnit.SECONDS);
        log.info("当前线程{} 收到{}消息：{}", Thread.currentThread().getId(), ctx.channel().id(), msg);
        ThreadUtil.sleep(5, TimeUnit.SECONDS);
        ctx.writeAndFlush(DateUtil.now() + " 收到 " + msg);

        //ThreadUtil.sleep(5, TimeUnit.SECONDS);
        //String msg2 = System.currentTimeMillis() + " From " + msg;
        //ctx.channel().writeAndFlush(msg2);
        //通过线程池进行业务处理才是最佳的实践啊，我们之前的处理方式都有点问题
        //executorService.submit(() -> {
        //
        //});
        log.info("{} Over", Thread.currentThread().getId());
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端上线：" + ctx.channel().id());
    }


}
